<template>
  <div class="register-container">
    <div class="register-card">
      <div class="register-header">
        <h2>学生注册</h2>
        <p>请填写以下信息完成注册</p>
      </div>
      
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        class="register-form"
        label-width="80px"
        size="large"
      >
        <!-- 角色选择 -->
        <el-form-item label="角色" prop="role">
          <el-select
            v-model="registerForm.role"
            placeholder="请选择角色"
            style="width: 100%"
            disabled
          >
            <el-option
              :value="0"
              label="学生"
            >
              <div class="role-option">
                <el-icon><User /></el-icon>
                <span>学生</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="学号" prop="studentId">
          <el-input
            v-model="registerForm.studentId"
            placeholder="请输入学号"
            clearable
            @blur="checkStudentId"
          />
        </el-form-item>
        
        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="registerForm.name"
            placeholder="请输入真实姓名"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="班级" prop="classId">
          <el-select
            v-model="registerForm.classId"
            placeholder="请选择班级"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="classItem in classList"
              :key="classItem.id"
              :label="`${classItem.grade} - ${classItem.name}`"
              :value="classItem.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
            clearable
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
            clearable
          />
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            @click="handleRegister"
            style="width: 100%"
          >
            注册
          </el-button>
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="text"
            @click="goToLogin"
            style="width: 100%"
          >
            已有账号？返回登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User } from '@element-plus/icons-vue'
import { registerApi, checkStudentIdApi } from '@/api/user/user'
import { getClassOptionsApi } from '@/api/class/class'

// 路由
const router = useRouter()

// 表单引用
const registerFormRef = ref()

// 加载状态
const loading = ref(false)

// 班级列表
const classList = ref([])

// 注册表单数据
const registerForm = reactive({
  role: 0, // 默认为学生角色
  studentId: '',
  name: '',
  classId: '',
  password: '',
  confirmPassword: ''
})

// 表单验证规则
const registerRules = {
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  studentId: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { min: 6, max: 20, message: '学号长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  classId: [
    { required: true, message: '请选择班级', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 检查学号是否存在
const checkStudentId = async () => {
  if (!registerForm.studentId) return
  
  try {
    await checkStudentIdApi(registerForm.studentId)
  } catch (error) {
    if (error.response?.status === 5001) {
      ElMessage.warning('该学号已被注册')
    }
  }
}

// 获取班级列表
const fetchClassList = async () => {
  try {
    // 现在后端已经放行了班级选项接口，可以直接调用API
    const response = await getClassOptionsApi()
    if (response.code === 200) {
      classList.value = response.data || []
    }
  } catch (error) {
    console.error('获取班级列表失败:', error)
    // 如果API调用失败，提供一些默认的班级选项
    classList.value = [
      { id: 1, grade: '2023级', name: '计算机科学与技术1班' },
      { id: 2, grade: '2023级', name: '计算机科学与技术2班' },
      { id: 3, grade: '2023级', name: '软件工程1班' },
      { id: 4, grade: '2023级', name: '软件工程2班' },
      { id: 5, grade: '2024级', name: '计算机科学与技术1班' },
      { id: 6, grade: '2024级', name: '计算机科学与技术2班' },
      { id: 7, grade: '2024级', name: '软件工程1班' },
      { id: 8, grade: '2024级', name: '软件工程2班' },
      { id: 9, grade: '2025级', name: '计算机科学与技术1班' },
      { id: 10, grade: '2025级', name: '计算机科学与技术2班' },
      { id: 11, grade: '2025级', name: '软件工程1班' },
      { id: 12, grade: '2025级', name: '软件工程2班' }
    ]
    ElMessage.warning('获取班级列表失败，使用默认数据')
  }
}

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  try {
    await registerFormRef.value.validate()
    
    loading.value = true
    
    const registerData = {
      studentId: registerForm.studentId,
      name: registerForm.name,
      classId: registerForm.classId,
      password: registerForm.password,
      role: registerForm.role
    }
    
    const response = await registerApi(registerData)

    if (response.code === 200) {
      ElMessage.success('注册成功！请返回登录页面登录')
      // 清空表单
      registerFormRef.value.resetFields()
      // 跳转到登录页
      setTimeout(() => {
        goToLogin()
      }, 1500)
    }
  } catch (error) {
    console.error('注册失败:', error)
  } finally {
    loading.value = false
  }
}

// 返回登录页
const goToLogin = () => {
  router.push('/login')
}

// 组件挂载时获取班级列表
onMounted(() => {
  fetchClassList()
})
</script>

<style lang="scss" scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url('@/assets/img/login-bg.jpg') no-repeat center center;
  background-size: cover;
  background-attachment: fixed;
  padding: 20px;
  position: relative;

  // 添加半透明遮罩层以确保内容可读性
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(64, 158, 255, 0.05);
    z-index: 1;
  }
}

.register-card {
  width: 100%;
  max-width: 450px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  border: 1px solid rgba(255, 255, 255, 0.2);
  position: relative;
  z-index: 2;
}

.register-header {
  text-align: center;
  padding: 40px 30px 20px;
  background: linear-gradient(135deg, #409eff 0%, #79bbff 100%);
  color: white;

  h2 {
    margin: 0 0 10px;
    font-size: 28px;
    font-weight: 600;
  }

  p {
    margin: 0;
    opacity: 0.9;
    font-size: 14px;
  }
}

.register-form {
  padding: 30px;

  .role-option {
    display: flex;
    align-items: center;
    gap: 8px;

    .el-icon {
      font-size: 16px;
      color: #409eff;
    }
  }

  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #333;
  }

  :deep(.el-input__wrapper) {
    border-radius: 8px;
    box-shadow: 0 0 0 1px #dcdfe6 inset;
    transition: all 0.3s;

    &:hover {
      box-shadow: 0 0 0 1px #c0c4cc inset;
    }

    &.is-focus {
      box-shadow: 0 0 0 1px #409eff inset;
    }
  }

  :deep(.el-select) {
    .el-input__wrapper {
      border-radius: 8px;
    }
  }

  :deep(.el-button) {
    border-radius: 8px;
    font-weight: 500;
  }
}

// 响应式设计
@media (max-width: 480px) {
  .register-container {
    padding: 10px;
    background-attachment: scroll; // 移动端使用scroll避免性能问题
  }

  .register-card {
    max-width: 100%;
  }

  .register-header {
    padding: 30px 20px 15px;

    h2 {
      font-size: 24px;
    }
  }

  .register-form {
    padding: 20px;
  }
}
</style>
